import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import {
  Row, Col, Card, Form, Input, Select,Radio, Icon, Button, Modal, message, Badge, Tag, DatePicker, InputNumber, Popconfirm
} from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './PaidMembership.less';
const RadioGroup = Radio.Group;
const { CheckableTag } = Tag;
const Search = Input.Search;
const formItemLayout = { labelCol: { span: 4 }, wrapperCol: { span: 20 } }
const FormItem = Form.Item;
const { Option } = Select;
let payCashNum = 0
let userPhoneData = {}
let inputUserPhones = ''
let userAssetData = {}
let payTypeVal ,messageData
const assetTypes =['月卡','季卡','半年 ','年卡']
let arr=[{ label: 'Apple', value: 'Apple' },{ label: 'Pear', value: 'Pear' },]
const CreateForm = Form.create()(props => {
  const { _handleOk,getUserPhoneInfo,getAssetConfig,getAssetConfigByRank,modalVisible, form, handleAdd, handleModalVisible, loading } = props;

  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      console.log(fieldsValue)
      _handleOk(fieldsValue);
    });
  };

  const onCancel = () => {
    handleModalVisible(false);
    form.resetFields();
  };

  const onChangeTypes = (e) => {
    const radioValue = e.target.value
    if(userAssetData){
      if(radioValue==1){
      const radioPay = userAssetData.purchase.filter(item => item.assetType===1)
      payCashNum = radioPay[0].payCash
    }
    if(radioValue==2){
      const radioPay = userAssetData.purchase.filter(item => item.assetType===2)
      payCashNum = radioPay[0].payCash
    }
    if(radioValue==3){
      const radioPay = userAssetData.purchase.filter(item => item.assetType===3)
      payCashNum = radioPay[0].payCash
    }
    if(radioValue==4){
      const radioPay = userAssetData.purchase.filter(item => item.assetType===4)
      payCashNum = radioPay[0].payCash
    }
    }
  }

  const userRankChange =(e)=>{
    const checkRadio =e.target.value
    if(userPhoneData){
      getAssetConfigByRank(checkRadio)
    }
    else{
      message.error('没有此手机号')
      //userPhoneData=null
    }
  }

  const getPhoneInfo =(e) =>{
    const inputUserPhone = e.target.value
    inputUserPhones = inputUserPhone
    const regtest=/^[1][3,4,5,7,8][0-9]{9}$/
    if(regtest.test(inputUserPhone)){
      getUserPhoneInfo(inputUserPhone)
    }
  }
  const payType =(e)=>{
    const payTypeValue = e.target.value
    if(userPhoneData){
       payTypeVal = payTypeValue
       if(payTypeValue==3||payTypeValue==4){
          getAssetConfig(payTypeValue)
       }
    }
  }

  return (
    <Modal
      title={"会员权益购买"}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={onCancel}
      width={700}
      confirmLoading={loading}
    >
      <FormItem {...formItemLayout} label="会员手机号">
        {form.getFieldDecorator('userPhone', {
          rules: [{
            required: true, message: '请正确输入手机号',
            pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/
             }],
        })(<Input onChange={getPhoneInfo} placeholder="请输入会员手机号" maxLength={11} />)}
      </FormItem>
      <FormItem {...formItemLayout} label="购买类型">
        {form.getFieldDecorator('ordersType', {
          rules: [{ required: true, message: '类型不能为空' }],
        })(
        <RadioGroup  onChange={payType}>
          <Radio value={1}>购买新会员</Radio>
          <Radio value={3}>升级vip会员</Radio>
          <Radio value={4}>续费会员</Radio>
        </RadioGroup>
        )}
      </FormItem>
      {
        payTypeVal == 1 ?(
          <FormItem {...formItemLayout} label="会员等级">
            {form.getFieldDecorator('orderTypeRank', {
              rules: [{ required: true, message: '等级不能为空' }],
              //initialValue: userPhoneData ? userPhoneData.userRank:null,
            })(
            <RadioGroup onChange={userRankChange} >
              <Radio value={1}>借阅会员</Radio>
              <Radio value={2}>vip会员</Radio>
            </RadioGroup>
            )}
          </FormItem>
          ):null
      }
      {
        payTypeVal == 1  ? (<div>
          <FormItem {...formItemLayout} label="有效期">
            {form.getFieldDecorator('assetType', {
              rules: [{ required: true, message: '有效期' }],
            })( 
                <RadioGroup onChange={onChangeTypes} >
                  {userAssetData && userAssetData.purchase  ?(
                    userAssetData.purchase.map(e=>{
                      if(e.assetType==1){
                        return <Radio value={1}>月卡{e.payCash}元</Radio>
                      }
                      if(e.assetType==2){
                        return <Radio value={2}>季卡{e.payCash}元</Radio>
                      }
                      if(e.assetType==3){
                        return <Radio value={3}>半年卡{e.payCash}元</Radio>
                      }
                      if(e.assetType==4){
                        return <Radio value={4}>年卡{e.payCash}元</Radio>
                      }
                    })
                    ):null}
                </RadioGroup>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="付款金额">
            {form.getFieldDecorator('payCash', {
              rules: [{ required: true, message: '付款金额' }],
              initialValue: payCashNum,
            })(<Input  maxLength={5} style={{border:'none',outline:'none'}} readOnly='true'/>)}
          </FormItem>
          </div>
          ):(null)
      }
      {
        payTypeVal == 3  ? (<div>
          <FormItem {...formItemLayout} label="剩余有效期">
            {form.getFieldDecorator('lastDay', {
              rules: [{ required: true, message: '剩余有效期' }],
              initialValue:userAssetData && userAssetData.upvip ? userAssetData.upvip.lastDay:null,
            })(<Input  maxLength={3} style={{border:'none',outline:'none'}} readOnly='true'/>)}
          </FormItem>
          <FormItem {...formItemLayout} label="付款金额">
            {form.getFieldDecorator('payCash', {
              rules: [{ required: true, message: '付款金额' }],
              initialValue: userAssetData && userAssetData.upvip ? userAssetData.upvip.payCash+'元':null,
            })(<Input  maxLength={5} style={{border:'none',outline:'none'}} readOnly='true'/>)}
          </FormItem>
          </div>
          ):(null)
      }
      {
        payTypeVal == 4  ? (<div>         
          <FormItem {...formItemLayout} label="有效期类型">
            {form.getFieldDecorator('assetType', {
              rules: [{ required: true, message: '有效期类型' }],
              initialValue: userAssetData && userAssetData.renew?(userAssetData.renew.assetType==1?"月卡":(userAssetData.renew.assetType==2?"季卡":(userAssetData.renew.assetType==3?"半年卡":"年卡"))):null
            })(<Input  maxLength={3} style={{border:'none',outline:'none'}} readOnly='true'/>)}
          </FormItem>
          <FormItem {...formItemLayout} label="付款金额">
            {form.getFieldDecorator('payCash', {
              rules: [{ required: true, message: '付款金额' }],
              initialValue: userAssetData && userAssetData.renew?userAssetData.renew.payCash+'元':null,
            })(<Input  maxLength={3} style={{border:'none',outline:'none'}} readOnly='true'/>)}
          </FormItem>
          </div>
          ):(null)
      }

    </Modal>
  );
});

@connect(({ member, loading }) => ({
  member,
  loading: loading.models.member,
}))
@Form.create()
export default class Member extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: true,
    selectedRows: [],
    formValues: {},
    startValue: null,
    endValue: null,
    begPayTime: null,
    endPayTime: null,
    checkedTag: null,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    const params ={
      pageNum:1,
      pageSize:10,  }
    dispatch({
      type: 'member/paidMemberList',
      payload: params ,
    });

  }

  handleStandardTableChange = (pagination) => {
    const { dispatch } = this.props;
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      ...this.props.form.getFieldsValue(),
    };
    dispatch({
      type: 'member/paidMemberList',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
      userPhone:null,
      userRank:null,
      ordersType:null,
      minCash:null,
      maxCash:null,
      startTime:null,
      endTime:null
    });
    dispatch({
      type: 'member/paidMemberList',
      payload: { pageNum: 1, pageSize: 10, },
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  _handleSearch() {
    const { dispatch, form } = this.props;
    const params = {
      pageNum: (this.props.member.paidMemberPagination && this.props.member.paidMemberPagination.current) ? this.props.member.paidMemberPagination.current : 1,
      pageSize: (this.props.member.paidMemberPagination && this.props.member.paidMemberPagination.pageSize) ? this.props.member.paidMemberPagination.pageSize : 10,
      ...this.props.form.getFieldsValue(),
      startTime: this.state.startValue ? this.state.startValue.format('YYYY-MM-DD HH:mm:mm') : null,
      endTime: this.state.endValue ? this.state.endValue.format('YYYY-MM-DD HH:mm:mm') : null,
    };
    console.log('params', params)
    dispatch({
      type: 'member/paidMemberList',
      payload: params,
    });
  };

getAssetConfig =(payTypeValue)=>{
  const { dispatch } = this.props;
    const params ={
      userId:userPhoneData.userId,
      userPhone:userPhoneData.userPhone,
      orderType:payTypeValue,
      userRank:userPhoneData.userRank,
      orderTypeRank:userPhoneData.userRank,
      assetType:userPhoneData.assetType,
      }
    dispatch({
      type: 'member/getUserAssetConfigure',
      payload: params ,
    });
}

getAssetConfigByRank =(checkRadio)=>{
  const { dispatch } = this.props;
    const params ={
      userId:userPhoneData.userId,
      userPhone:userPhoneData.userPhone,
      orderType:payTypeVal,
      userRank:userPhoneData.userRank,
      orderTypeRank:checkRadio,
      assetType:userPhoneData.assetType,
      }
    dispatch({
      type: 'member/getUserAssetConfigure',
      payload: params ,
    });
}

  getUserPhoneInfo = (inputUserPhone)=>{
    const { dispatch } = this.props;
    const params ={
      userPhone:inputUserPhone,
      }
    dispatch({
      type: 'member/getPhoneUserList',
      payload: params ,
    });
  }
  handleModalVisible = flag => {
    if (!flag) {
      console.log('222')
      this.setState({
        modalTitle: '会员权益购买',
        modalVisible: !!flag,
      }); 
       payTypeVal=''  
    } else {
      this.setState({
        modalVisible: !!flag,
      });
    }
  };
  
  _handleOk = (fields, form) => {
    console.log(fields)
      if(userPhoneData){
        if(fields.hasOwnProperty('payCash')){
          if(typeof(fields.payCash) == 'string'){
            console.log('payCash')
            fields.payCash=parseFloat(fields.payCash.substr(0, fields.payCash.length - 1));
          }
         }
         if(fields.hasOwnProperty('lastDay')){
          if(typeof(fields.payCash) == 'string'){
          fields.lastDay=parseInt(fields.payCash.substr(0, fields.lastDay.length - 1));
          console.log(fields.lastDay)
          }
         }
       if(payTypeVal==4){
        var assettypeVal =0
        assetTypes.map((e,ind)=>{
          if(fields.assetType == e){
            console.log(ind+1)
            return assettypeVal= ind+1
          }
        })
        var params = {
          ...fields,
          assetType:assettypeVal,
          userId:userPhoneData.userId,
          userRank:userPhoneData.userRank,
          endTime:userPhoneData.endTime,
          lastDay:userPhoneData.lastDay,
        }
       }else{
        var params = {
          ...fields,
          //assetType:assettypeVal,
          userId:userPhoneData.userId,
          userRank:userPhoneData.userRank,
          endTime:userPhoneData.endTime,
        }
       }
      const { dispatch } = this.props;
      dispatch({
        type: 'member/sumbitAssetOrders',
        payload: params,
        callback: () => { this.handleFormReset();this.handleModalVisible(false); }
      });
    }else {
      message.error('没有此手机号')  
      } 
  };


  disabledStartDate = (startValue) => {
    const endValue = this.state.endValue;
    if (!startValue || !endValue) {
      return false;
    }
    return startValue.valueOf() > endValue.valueOf();
  }

  disabledEndDate = (endValue) => {
    const startValue = this.state.startValue;
    if (!endValue || !startValue) {
      return false;
    }
    return endValue.valueOf() <= startValue.valueOf();
  }

  onChange = (field, value) => {
    this.setState({
      [field]: value,
    });
  }

  onStartChange = (value) => {
    this.onChange('startValue', value);
  }

  onEndChange = (value) => {
    this.onChange('endValue', value);
  }


  disabledStartDate1 = (startValue) => {
    const endValue = this.state.endValue;
    if (!startValue || !endValue) {
      return false;
    }
    return startValue.valueOf() > endValue.valueOf();
  }

  disabledEndDate1 = (endValue) => {
    const startValue = this.state.startValue;
    if (!endValue || !startValue) {
      return false;
    }
    return endValue.valueOf() <= startValue.valueOf();
  }

  onStartChange1 = (value) => {
    this.onChange('begPayTime', value);
  }

  onEndChange1 = (value) => {
    this.onChange('endPayTime', value);
  }






  renderAdvancedForm() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form layout="inline">
      <div style={{ overflow: 'hidden' }}>
          <span style={{ float: 'right', marginBottom: 24 }}>
            <Button type="primary" htmlType="submit" onClick={() => this._handleSearch()}>
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
          </span>
        </div>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="手机号">
              {getFieldDecorator('userPhone')(<Input placeholder="请输入"  />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
             <FormItem label="会员等级">
              {getFieldDecorator('userRank', { initialValue: 'undefined' })(
                <Select
                style={{ width: '100%' }}>
                  <Option value="undefined">全部</Option>
                  <Option value="0">普通会员</Option>
                  <Option value="1">借阅会员</Option>
                  <Option value="2">VIP会员</Option>
                </Select>)
              }
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="会员ID">
              {getFieldDecorator('userId')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="消费类型">
              {getFieldDecorator('ordersType', { initialValue: 'undefined' })(
                <Select
                // showSearch
                filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                style={{ width: '100%' }}>
                  <Option value="undefined">全部</Option>
                  <Option value="1">开通借阅会员</Option>
                  <Option value="2">开通vip会员</Option>
                  <Option value="3">升级vip会员</Option>
                  <Option value="4">续费会员</Option>
                </Select>)
              }
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="消费金额">
              {getFieldDecorator('minCash')(<InputNumber placeholder="最小金额" min={1} />)}
              {'-'}
              {getFieldDecorator('maxCash')(<InputNumber placeholder="最大金额" min={1} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="消费时间" style={{width:'58%',float:'left'}}>
              {getFieldDecorator('startTime')(
                <DatePicker
                  disabledDate={this.disabledStartDate}
                  showTime
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder="开始时间"
                  onChange={this.onStartChange}
                />
              )}
            </FormItem>
            <FormItem label="" style={{width:'38%',float:'right'}}>
              {getFieldDecorator('endTime')(
                <DatePicker
                  disabledDate={this.disabledEndDate}
                  showTime
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder="结束时间"
                  onChange={this.onEndChange}
                />
              )}
            </FormItem>
          </Col>
        </Row>

      </Form>
    );
  }

  renderForm() {
    return  this.renderAdvancedForm();
  }


  render() {
    const tableData = {}
    const {member} = this.props
    tableData['list'] = this.props.member.paidMemberData;
    tableData['pagination'] = this.props.member.paidPagination;
    const { selectedRows, modalVisible } = this.state;
    userPhoneData = member.phoneList[0]
    userAssetData = member.AssetConfigData
    messageData = member.AssetConfigData
    console.log(member)
    const columns = [
      {
        title: '会员Id',
        dataIndex: 'userId',
        key: 'userId',
      },
      {
        title: '手机号',
        dataIndex: 'userPhone',
        key: 'userPhone',
      },
      {
        title: '会员等级',
        dataIndex: 'userRank',
        key: 'userRank ',
        render(val) {
          return <span>{val == '1' ? '借阅会员' : val == '2' ? 'VIP会员' : '普通会员'}</span>;
        },
      },
      {
        title: '消费类型',
        dataIndex: 'ordersType',
        key: 'ordersType',
        render(val) {
          return <span>{val == '1' ? ('开通借阅会员'):( val == '2' ? ('开通vip会员') : (val == '3' ? '升级vip会员' :(val =='4'? '续费会员':null)))}</span>;
        },
      },
      {
        title: '消费金额',
        dataIndex: 'payCash',
        key: 'payCash',
      },
      {
        title: '支付方式',
        dataIndex: 'payType',
        key: 'payType',
        render(val) {
          return <span>{val == '0' ? '线上支付' : val == '1' ? '线下支付' : null}</span>;
        },
      },

      {
        title: '消费时间',
        dataIndex: 'createTime',
        key: 'createTime',
      }
    ];

    const parentMethods = {
      _handleOk:this._handleOk,
      handleModalVisible: this.handleModalVisible,
      getUserPhoneInfo:this.getUserPhoneInfo,
      getAssetConfig:this.getAssetConfig,
      getAssetConfigByRank:this.getAssetConfigByRank,
    };

    return (
      <PageHeaderLayout title="">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              <Button type="primary" onClick={() => this.handleModalVisible(true)} >
                会员权益购买
              </Button>
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={this.props.loading}
              data={tableData}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
              rowKey="userId"
            />
          </div>
        </Card>
        <CreateForm {...parentMethods} modalVisible={modalVisible}
          handleOk={(fieldsValue, form) => this._handleOk(fieldsValue, form)}  loading={this.props.loading}
        />
      </PageHeaderLayout>
    );
  }
}
